package pl.mchaniewski.ryneczek.web.admin;

import javax.faces.application.FacesMessage;
import javax.faces.event.ComponentSystemEvent;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Email;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;

import pl.mchaniewski.ryneczek.pojo.User;
import pl.mchaniewski.ryneczek.services.UserService;
import pl.mchaniewski.ryneczek.utilities.FacesMessageUtil;
import pl.mchaniewski.ryneczek.utilities.I18nUtil;
import pl.mchaniewski.ryneczek.utilities.NavigationUtil;
import pl.mchaniewski.ryneczek.web.FormButton;

@Component
@Scope("request")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public class UserDetailsBean extends FormButton {
    private UserService userService;

    /* Form */
    @Size(max = 30, message = "{registerbean.loginSize}")
    @Email(message = "{registerbean.loginEmail}")
    private String login;
    @Size(min = 5, max = 30, message = "{registerbean.passwordSize}")
    private String pass1;
    @Size(min = 5, max = 30, message = "{registerbean.passwordSize}")
    private String pass2;
    private User user;

    /* Request parameters */
    private Integer id;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public String getLogin() {
        if (getUser() != null) {
            return getUser().getLogin();
        }

        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getPass1() {
        return pass1;
    }

    public void setPass1(String pass1) {
        this.pass1 = pass1;
    }

    public String getPass2() {
        return pass2;
    }

    public void setPass2(String pass2) {
        this.pass2 = pass2;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public User getUser() {
        if (user != null) {
            if (user.getUserid().equals(id)) {
                return user;
            }
        }

        if (id != null) {
            user = userService.findById(id);
            return user;
        }

        return null;
    }

    public void init(ComponentSystemEvent event) {
        if (id == null) {
            NavigationUtil.directRedirect(NavigationUtil.DIRECT_USER_LIST);
        }

        if (getUser() == null) {
            NavigationUtil.directRedirect(NavigationUtil.DIRECT_USER_LIST);
        }
    }

    public String saveDetails() {
        if (getUser() == null) {
            FacesMessageUtil
                    .addMessage(
                            getButton(),
                            I18nUtil.getLocalizedMessage("userdetailsbean.noUserFound"),
                            FacesMessage.SEVERITY_ERROR);

            return NavigationUtil.USER_LIST;
        } else {
            if (!getPass1().equals(getPass2())) {
                FacesMessageUtil.addMessage(getButton(), I18nUtil
                        .getLocalizedMessage("changepasswordbean.doesntMatch"),
                        FacesMessage.SEVERITY_ERROR);

                return NavigationUtil.SAME_PAGE;
            }

            if (!getUser().getLogin().equals(getLogin().toLowerCase())
                    && userService.findByLogin(getLogin().toLowerCase()) != null) {
                FacesMessageUtil.addMessage(getButton(), I18nUtil
                        .getLocalizedMessage("registerbean.loginExists"),
                        FacesMessage.SEVERITY_ERROR);

                return NavigationUtil.SAME_PAGE;
            }

            if (userService
                    .changeLoginAndPassword(getUser(), login, getPass1()) != null) {
                FacesMessageUtil.addMessage(getButton(), I18nUtil
                        .getLocalizedMessage("userdetailsbean.userSaved"),
                        FacesMessage.SEVERITY_INFO);
            } else {
                FacesMessageUtil.addMessage(getButton(), I18nUtil
                        .getLocalizedMessage("userdetailsbean.userNotSaved"),
                        FacesMessage.SEVERITY_ERROR);
            }

            return NavigationUtil.SAME_PAGE;
        }
    }

    public String blockUser() {
        if (getUser() == null) {
            FacesMessageUtil
                    .addMessage(
                            getButton(),
                            I18nUtil.getLocalizedMessage("userdetailsbean.noUserFound"),
                            FacesMessage.SEVERITY_ERROR);

            return NavigationUtil.USER_LIST;
        } else {
            getUser().setUserFlags(true, User.IS_BLOCKED);
            if (userService.save(getUser()) != null) {
                FacesMessageUtil
                        .addMessage(
                                getButton(),
                                I18nUtil.getLocalizedMessage("userdetailsbean.blocked"),
                                FacesMessage.SEVERITY_INFO);
            } else {
                FacesMessageUtil.addMessage(getButton(), I18nUtil
                        .getLocalizedMessage("userdetailsbean.blockError"),
                        FacesMessage.SEVERITY_ERROR);
            }

            return NavigationUtil.SAME_PAGE;
        }
    }

    public String unblockUser() {
        if (getUser() == null) {
            FacesMessageUtil
                    .addMessage(
                            getButton(),
                            I18nUtil.getLocalizedMessage("userdetailsbean.noUserFound"),
                            FacesMessage.SEVERITY_ERROR);

            return NavigationUtil.USER_LIST;
        } else {
            getUser().setUserFlags(false, User.IS_BLOCKED);
            if (userService.save(getUser()) != null) {
                FacesMessageUtil.addMessage(getButton(), I18nUtil
                        .getLocalizedMessage("userdetailsbean.unblocked"),
                        FacesMessage.SEVERITY_INFO);
            } else {
                FacesMessageUtil.addMessage(getButton(), I18nUtil
                        .getLocalizedMessage("userdetailsbean.blockError"),
                        FacesMessage.SEVERITY_ERROR);
            }

            return NavigationUtil.SAME_PAGE;
        }
    }

    public String removeUser() {
        if (getUser() == null) {
            FacesMessageUtil
                    .addMessage(
                            I18nUtil.getLocalizedMessage("userdetailsbean.noUserFound"),
                            FacesMessage.SEVERITY_ERROR);
        } else {
            String userLogin = getUser().getLogin();

            if (userService.remove(getUser())) {
                FacesMessageUtil
                        .addMessage(
                                I18nUtil.getLocalizedMessage("userdetailsbean.userDeleted")
                                        + " Login: " + userLogin,
                                FacesMessage.SEVERITY_INFO);
            } else {
                FacesMessageUtil.addMessage(I18nUtil
                        .getLocalizedMessage("userdetailsbean.deleteError"),
                        FacesMessage.SEVERITY_ERROR);
            }
        }

        return NavigationUtil.USER_LIST;
    }

}
